﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace DDOS
{
    /// <summary>
    /// Example usage:
    /// 
    /// Camera2D cam = new Camera2D(position, zoom, rotation);
    /// sb.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, null, cam.GetTransform(Game1.Resolution));
    /// 
    /// You can calculate a zoom value to make the game resolution independent with:
    /// float zoom = Math.Max(Game1.Resolution.X / 1920, Game1.Resolution.Y / 1080);
    /// Where the 1920x1080 is the native resolution, and the Resolution vector contains the actual resolution
    /// </summary>
    public class Camera2D
    {
        private float zoom;
        private float angle;
        private Vector2 position;
        private Matrix transform;

        public float Zoom
        {
            get { return zoom; }
            set { zoom = value; if (zoom < 0.1f) zoom = 0.1f; }
        }
        public float Angle
        {
            get { return angle; }
            set { angle = value; }
        }
        public Vector2 Position
        {
            get { return position; }
            set { position = value; }
        }
        public Matrix Transform
        {
            get { return transform; }
        }

        public Camera2D(Vector2 pos, float zoom, float angle)
        {
            Position = pos;
            Zoom = zoom;
            Angle = angle;
        }

        public void Move(Vector2 v)
        {
            Position += v;
        }

        public Matrix GetTransform(Vector2 Viewport)
        {
            transform = Matrix.CreateTranslation(new Vector3(-Position.X, -Position.Y, 0)) *
                                         Matrix.Identity *
                                         Matrix.CreateRotationZ(Angle) *
                                         Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
                                         Matrix.CreateTranslation(new Vector3(Viewport.X * 0.5f, Viewport.Y * 0.5f, 0));
            return transform;
        }

        public Vector2 ToRelativeLocation(Vector2 position)
        {
            return Vector2.Transform(position, transform);
        }
        public Vector2 ToWorldLocation(Vector2 position)
        {
            return Vector2.Transform(position, Matrix.Invert(transform));
        }
    }
}

